<extend name="Public/base" />

<block name="style" >
    <style>
        .user_table{
            border: 1px solid #ddd;
            width: 180px;
        }
        .user_table tr{
            border: 1px solid #dddddd;
            height: 30px;
        }
        .user_table td{
            border: 1px solid #dddddd;
            width: 90px;
            text-align: center;
        }
        .list-inline > li{width:30%;}
    </style>
</block>

<block name="body">
    <!-- 弹窗插件 -->
    <include file="Public:artdialog" />
    <!-- 表单验证插件 -->
    <include file="Public:validform" />

    <form action="{:U('addsale')}" method="post" role="form" class="form-horizontal row-border vform" id="formid" >  
        <div class="row">
            <div class="col-md-12">
                <div class="block-web">
                    <div class="header">
                       <div class="actions_diy">
                           <a href="javascript:;" id="add_edit_id" class="btn btn-default btn-primary">
                               <i class="fa fa-plus"></i>选择特价商品
                           </a>
	                  </div>
	                   <h3 class="content-header">特价商品信息</h3>
                    </div>
                    <div class="porlets-content">  
                        
                         <div class="form-group">
                            <label class="col-sm-3 control-label"><font class="red">*</font>特价主题</label>
                            <div class="col-sm-3">
                                 <select name="saleid" id="saleid">
                                        <option item="{:u('Special/add')}" value="">全部</option>
                                        <volist name="sort" id="s"> 
                                          <option item="{:u('Special/add',array('saleid'=>$s['saleid']))}" value="{$s.saleid}" <if condition="$s['saleid'] eq $sid">selected="selected"</if>>{$s.salename}</option>
                                        </volist>
                                 </select>   
                            </div>
                        </div>     
                            <ul class="list-inline" id="salegoodsid">
                              <li>商品名称</li> <li>单位</li> <li>价格</li>
                              <volist name="ls" id="o">
                                <li>{$o.goodsname}</li> <li>{$o.unit}</li><li><input type="text" value="{$o.price}" field='"listid":"{$o.listid}","saleid":"{$o.saleid}","goodsid":"{$o.goodsid}","goodsname":"{$o.goodsname}","price":"{$o.price}","unit":"{$o.unit}"'></li>
                              </volist>
                            </ul>
                         
                        <div class="form-group">
                            <label class="col-sm-3 control-label"></label>
                            <button class="btn btn-primary btn-success bt_submit" type="button" id="submit">提交</button>
                        </div>
                    </div><!--/porlets-content-->
                </div><!--/block-web-->
            </div> 
        </div> 
    </form> 

</block>
<block name="script">
<script type="text/javascript" src="__PUBLIC__/Admin/js/json2.js"></script>
<script type="text/javascript" src="__PUBLIC__/Admin/js/common_manage.js""></script>
<script type="text/javascript">
//定义cookiename
var cookiename="goods_<?php echo UID; ?>";
var reg=/^\d+(\.\d{0,2})?$/;
var sid="{$sid}";
var backurl="{:u('Special/index')}";
 
$(function(){
  $("#add_edit_id").bind("click",fnadd);  
  $("select[name='saleid']").val(sid);
  $("#submit").bind("click",checkdata);
  $("#saleid").bind("change",gourl);
  var _list=getCookie(cookiename);
  if(_list){
	  fnCreateGoodsList();
  }
});


var gourl=function(){
	var _url=$(this).find("option:selected").attr("item");
	location.replace(_url);
}
 
 var fnadd = function(){
   
    var url="{:U('Specialoffer/selection_of_goods')}";
    title="选择特价商品";  
    var mydialog=art.dialog.open(url,{title:title, width:'1200px', height:'80%', opacity: 0.2, id: "add_edit_id",
  	  ok: function () { 
  		    this.close();
  		    fnCreateGoodsList();
  	        return false;
  	    },
  	    okVal:'确定',
  	    cancelVal: '取消',
  	    cancel: function(){this.close();}	
  });  
 }
 
 //添加修改时，构建商品价格信息，并过滤存在的商品记录
 var fnCreateGoodsList = function(){
	 
	 var ojson=[],lsjson=[],json=[]; 
	 var htl="";
	//获取cookie值 
	var _list=getCookie(cookiename);
	if(_list!=""){
	  ojson=JSON.parse(_list);
	} 
	
	//当前已经存在的商品信息 
	$("input[type='text']").each(function(){
		var _json=$(this).attr("field");
		var _json="{"+_json+"}"
		var tmp =JSON.parse(_json);
		var _val=$(this).val();
		if(!isNaN(_val) && reg.test(_val)){
		   tmp.price=_val;
		   var _jsonstr=JSON.stringify(tmp);
		    _jsonstr=_jsonstr.replace("{","").replace("}","");
		   $(this).attr("field",_jsonstr)
		}
		lsjson.push(tmp);  //当前特价商品信息
	});
	
	//过滤存在的商品信息 
	for(var i=0;i<ojson.length;i++){
		var flg=false;
		for(var j=0;j<lsjson.length;j++){
			if(ojson[i].goods_id==lsjson[j].goodsid){
				flg=true;
				break;
			}
		}
		if(!flg){json.push(ojson[i]);}
	}
	
	 //alert(_list);
	
	if(json.length==0)return;
	for(var i=0;i<json.length;i++){
		htl+='<li>'+json[i].goods_name+'</li><li>'+json[i].measure_unit+'</li><li><input type="text" value="'+json[i].sale_price+'" field=\'"listid":"","saleid":"'+sid+'","goodsid":"'+json[i].goods_id+'","goodsname":"'+json[i].goods_name+'","price":"'+json[i].sale_price+'","unit":"'+json[i].measure_unit+'"\'></li>';
	}
	if(htl!=""){
		$("#salegoodsid").append(htl);    
	} 
 }
 
 
 var  getdatalist=function(){
	 var lsjson=[];
   //当前已经存在的商品信息 
	$("input[type='text']").each(function(){
		var _json=$(this).attr("field");
		var _json="{"+_json+"}"
		var tmp =JSON.parse(_json);
		var _val=$(this).val();
		if(!isNaN(_val) && reg.test(_val)){
		   tmp.price=_val;
		   tmp.saleid=_sidval;
		}
		//价格大于0才添加，否则删除信息。
		if(parseInt(_val)>0){
		  lsjson.push(tmp);  //当前特价商品信息
		}
	});
   
   return lsjson;   
 }
 
 var _flg=false;
 var datajson=[];//获取所有列表的商品价格信息数据
 var _sidval=""; //全局变量，选中主题编号
 
 //检查数据是否符合条件
 var checkdata=function(){ 
	   
	 _sidval=$("#saleid").val();
	
	 if(_sidval==""){
		 art.dialog({title:'温馨提示',content: '请选择特价主题！', ok: function () {this.close();return false;},okval:'确定'}); 
		 return false;
	 } 
	 
	datajson= getdatalist();
	
	if(!datajson|| datajson.length==0){
		art.dialog({title:'温馨提示',content: '没有任何商品信息，请添加商品或者设置价格!', ok: function () {this.close();return false;},okval:'确定'});  
		return false;
	} 
	
	 if(sid!="" && _sidval!=sid){
		 art.dialog({
			    title:'温馨提示',
			    content: '特价主题与当前选中的主题不一致，是否继续添？',
			    ok: function () { 
			    	_flg=true;
			    	salesave();
			    	this.close();
			        return false;
			    },
			    cancelVal: '关闭',
			    cancel: true //为true等价于function(){}
	   }); 
   }else{
	  _flg=true;
      salesave(); 
   } 
 }
 
 //提交数据保存特价商品信息，检测记录信息
 var salesave=function()
 {
	  
	if(!_flg||!datajson){return false;}
	 var _sidval=$("#saleid").val();
	 var url=$("#formid").attr("action");
	 var postdata=JSON.stringify(datajson)
	 $.ajax({
         'url': url,
         'data': {sid:_sidval,json:postdata},
         'dataType': 'json',
         'type': 'POST',
         success: function (data) {
        	 
        	 if(!data){
        		 art.dialog({title:'温馨提示',content: '提交数据保存失败', ok: function () {this.close();return false;},okval:'确定'});
        		 return;
        	 }  
        	
             if (data.staute =="success") {  
            	 setCookie(cookiename,"",-10); //清理cookie信息
            	 art.dialog({title:'温馨提示',content: data.msg, ok: function () {this.close();location.href=backurl;return false;},okval:'确定'}); 
             }
             else{
            	 art.dialog({title:'温馨提示',content: data.msg, ok: function () {this.close();return false;},okval:'确定'}); 
             }

         }, error: function (err) { 
        	 
        	 art.dialog({title:'温馨提示',content: err.responseText, ok: function () {this.close();return false;},okval:'确定'});
         },complete: function () {
            
         }
     });  
 }
</script>
</block>
